package com.car.web.controller;

import com.car.pojo.SysUser;
import com.car.service.SysUserMapperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class CarController {

    @Autowired
    private SysUserMapperService service;

    @GetMapping(value = "/list")
    public String list(Model model, SysUser sysUser, @RequestParam(defaultValue = "1") Integer pageNo) {
        Integer pageSize = 3;
        List<SysUser> list = service.list(sysUser, pageSize, pageNo);
        model.addAttribute("list", list);
        Integer totalCount = service.selectSysUserCount(sysUser);
        Integer totalPages = totalCount / pageSize;
        if (totalCount % pageSize != 0) {
            totalPages++;
        }
        model.addAttribute("list", list);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageNo", pageNo);
        model.addAttribute("pageSize", pageSize);
        return "index_v1";
    }

    @PostMapping("/add")
    public String add(SysUser sysUser) {
        int result = service.add(sysUser);
        if (result > 0) {
            return "redirect:list";
        }
        return "add";
    }

    @GetMapping("/delete")
    public String delete(@RequestParam Integer user_id) {
        int result = service.delete(user_id);
        if (result > 0) {
            return "redirect:list";
        }
        return "delete";
    }

    @PostMapping("/toEdit")
    public String toEdit(SysUser sysUser) {
        int result = service.update(sysUser);
        if (result > 0) {
            return "redirect:list";
        }
        return "toEdit";
    }

    @GetMapping("/edit")
    public String edit(Model model, Integer user_id) {
        SysUser sysUser = service.getByid(user_id);
        model.addAttribute("sysUser", sysUser);

        return "edit";
    }

}
